package com.epoch.platform.sys.org.controller;

import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.base.BaseController;
import com.epoch.base.util.AjaxResult;
import com.epoch.platform.sys.org.dao.SysOrg;
import com.epoch.platform.sys.org.service.SysOrgService;
import com.epoch.platform.sys.user.dao.SysUser;
import com.epoch.platform.sys.userorg.dao.SysUserOrg;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;

@ControllerBind(controllerKey = "/sys/org")
public class SysOrgController extends BaseController{
	
	AjaxResult ajaxResult = new AjaxResult();
	
	SysOrgService sysOrgService = new SysOrgService();
	
	public void index() {
		this.render("/sys/dept/sys_dept_tab.html");
	}
	
	public void listUI() {
		this.render("/sys/dept/sys_dept_list.html");
	}

    public void findOrgListAjax() {
    	Kv param = Kv.create();
    	SqlPara sqlPara = Db.getSqlPara("systemManage.findAllSysOrgList", param);
    	List<SysOrg> sysOrgList = SysOrg.dao.find(sqlPara);
        renderJson(new Page<>(sysOrgList, 1, 1, 1, sysOrgList.size()));
    }
    
    public void suvUI() {
        String id = getPara("ID");
        String parentId = getPara("parentId");
        setAttr("parentId", parentId);
        String parentName = getPara("parentName");
        if(null == parentName) {
        	setAttr("parentName", "组织树");
        }else {
        	setAttr("parentName", parentName);
        }
        SysOrg sysOrg;
        if (StringUtils.isNotBlank(id)) {
            sysOrg = SysOrg.dao.findById(id);
            SysOrg sysOrgParent = SysOrg.dao.findById(sysOrg.getStr("parent_id"));
            if (sysOrgParent != null) {
                setAttr("parentId", sysOrg.getStr("parent_id"));
                setAttr("parentName", sysOrgParent.getStr("org_name"));
            }
        } else {
            sysOrg = new SysOrg();
        }
        setAttr("sysOrg", sysOrg);
        setAttr("treeNodeJson", JSON.toJSON(sysOrgService.getAllTreeOrgList()));
        render("/sys/dept/sys_dept_edit.html");
    }
    
    /**
     * 组织分配用户
     */
    public void saveSysOrgUser() {
        String[] userIds = getParaValues("userId[]");
        String orgId = getPara("orgId");
        try {
            if (ArrayUtils.isNotEmpty(userIds)) {
                for (String userId : userIds) {
                    SysUserOrg userOrgBean = SysUserOrg.dao.findFirst(Db.getSql("systemManage.findUserOrgByUserId"), userId);
                    SysUser user = SysUser.dao.findById(userId);
                	user.set("DEPT_ID", orgId);
                	user.set("COMPANY_ID", orgId);
                    if (userOrgBean == null) {
                    	SysUserOrg userOrg = new SysUserOrg();
                        userOrg.set(SysUserOrg.ORG_ID, orgId);
                        userOrg.set(SysUserOrg.USER_ID, userId);
                        userOrg.saveOrUpdate();
                    }else {
                    	userOrgBean.set(SysUserOrg.ORG_ID, orgId);
                    	userOrgBean.saveOrUpdate();
                    }
                    user.saveOrUpdate();
                }
            }
            ajaxResult.success("保存成功。");
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult.addError("保存失败。");
        }
        renderJson(ajaxResult);
    }
	
    /**
     * 保存或更新
     */
    public void saveOrUpdate() {
        /**
         * 获取表单
         */
    	SysOrg sysOrg = null;
        try {
        	 sysOrg  = getModel(SysOrg.class, "sysOrg", true);
            sysOrg.saveOrUpdate();
            ajaxResult.setData(sysOrg.getStr(SysOrg.ID));
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult.addError("保存失败。");
        }
        renderJson(ajaxResult);
    }
    
    public void findSysUserByOrgId() {
        // 保存一个AjaxResult对象进入域中
        Kv param = commonParams();
        String parentId = null;
        if (getPara("org_id") != null) {// 主键id
            parentId = getPara("org_id");
        }
        //获取父类节点parentId
        param.set("org_id", parentId);
        // 查找组织id为orgId的用户_组织列表
        Page<SysOrg> userOrgList = SysOrg.dao.paginate(Db.getSqlPara("systemManage.findSysUserByOrgId", param), param);
        renderJson(userOrgList);
    }
    
    /**
     * 删除
     */
    public void deleteUser() {
        String[] ids = getParaValues("ids[]");
        try {
            if (ArrayUtils.isNotEmpty(ids)) {
                for (String id : ids) {
                	//将用户表中的用户与组织的对应关系删除
                	SysUser user =  SysUser.dao.findFirst(Db.getSql("systemManage.findSysUserByUserId"), id);
                	user.set("DEPT_ID", "0");
                	user.set("COMPANY_ID", "0");
                	user.update();
                    // 根据角色id删除角色组织对应关系表中的内容
                    Db.update(Db.getSql("systemManage.deleteSysUserOrgByUserId"), id);
                }
            }
            ajaxResult.success("删除成功。");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.addError("删除失败。");
        }
        renderJson(ajaxResult);
    }
    
    /**
     * 删除
     */
    public void delete() {
        String[] ids = getParaValues("ids[]");
        try {
            if (ArrayUtils.isNotEmpty(ids)) {
                for (String id : ids) {
                    SysOrg.dao.deleteById(id);
                    Db.update(Db.getSql("systemManage.deleteUserOrgByParentId"), id);
                    // 删除该组织下的所有用户
                    Db.update(Db.getSql("systemManage.deleteUserOrgByOrgId"), id);
                }
            }
            ajaxResult.success("删除成功。");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.addError("删除失败。");
        }
        renderJson(ajaxResult);
    }

}
